// 加载环境变量
require('dotenv').config();

const express = require('express');
const QRCode = require('qrcode');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const https = require('https'); // 使用原生https模块
const axios = require('axios'); // 使用axios替代fetch
const config = require('./config'); // 引入配置文件
const bcrypt = require('bcryptjs');

const app = express();
const PORT = config.port;

// 数据文件路径
const DATA_FILE = config.dataFile;
const COMMUNITIES_FILE = config.communitiesFile;

// 系统配置
console.log('系统启动中...');

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

// 配置信任代理，用于获取真实客户端IP
app.set('trust proxy', true);

// 初始化数据文件
function initDataFiles() {
    try {
        if (!fs.existsSync(DATA_FILE)) {
            const initialData = {
                scanRecords: [],
                totalScans: 0
            };
            fs.writeFileSync(DATA_FILE, JSON.stringify(initialData, null, 2));
            console.log('数据文件创建成功:', DATA_FILE);
        }
        
        if (!fs.existsSync(COMMUNITIES_FILE)) {
                            const initialCommunities = {
                    communities: [
                        { id: 1, name: '天龙地区', active: true },
                        { id: 2, name: '阳光花园', active: true },
                        { id: 3, name: '翠湖庄园', active: true }
                    ]
                };
                fs.writeFileSync(COMMUNITIES_FILE, JSON.stringify(initialCommunities, null, 2));
                console.log('地区文件创建成功:', COMMUNITIES_FILE);
        }
        
        // 初始化系统配置文件
        if (!fs.existsSync(config.configFile)) {
            const initialConfig = {
                targetUrl: config.targetUrl,
                baseUrl: config.baseUrl,
                lastUpdated: new Date().toISOString()
            };
            fs.writeFileSync(config.configFile, JSON.stringify(initialConfig, null, 2));
            console.log('系统配置文件创建成功:', config.configFile);
        } else {
            // 读取现有配置并更新内存中的配置
            try {
                const systemConfig = readSystemConfig();
                config.targetUrl = systemConfig.targetUrl || config.targetUrl;
                config.baseUrl = systemConfig.baseUrl || config.baseUrl;
                console.log('系统配置已加载:', systemConfig);
            } catch (error) {
                console.error('加载系统配置失败:', error);
            }
        }
    } catch (error) {
        console.error('初始化数据文件失败:', error);
    }
}

// 读取数据
function readData() {
    try {
        const data = fs.readFileSync(DATA_FILE, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return { scanRecords: [], totalScans: 0 };
    }
}

// 保存数据
function saveData(data) {
    try {
        fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
        console.log('数据保存成功，总扫码次数:', data.totalScans);
    } catch (error) {
        console.error('保存数据失败:', error);
    }
}

// 读取地区列表
function readCommunities() {
    try {
        const data = fs.readFileSync(COMMUNITIES_FILE, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return { communities: [] };
    }
}

// 保存地区列表
function saveCommunities(data) {
    try {
        fs.writeFileSync(COMMUNITIES_FILE, JSON.stringify(data, null, 2));
        console.log('地区数据保存成功');
    } catch (error) {
        console.error('保存地区数据失败:', error);
    }
}

// 读取系统配置
function readSystemConfig() {
    try {
        const data = fs.readFileSync(config.configFile, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return {
            targetUrl: config.targetUrl,
            baseUrl: config.baseUrl,
            lastUpdated: new Date().toISOString()
        };
    }
}

// 保存系统配置
function saveSystemConfig(data) {
    try {
        fs.writeFileSync(config.configFile, JSON.stringify(data, null, 2));
        console.log('系统配置保存成功');
    } catch (error) {
        console.error('保存系统配置失败:', error);
    }
}

// 初始化数据
initDataFiles();

// 系统工具函数
function formatDate(date) {
    return new Date(date).toLocaleString('zh-CN');
}

// 解析设备信息
function parseUserAgent(userAgent) {
    if (!userAgent) {
        return {
            system: '未知',
            software: '未知',
            networkType: '未知',
            deviceType: '未知'
        };
    }

    const result = {
        system: '未知',
        software: '未知',
        networkType: '未知',
        deviceType: '未知'
    };

    // 解析系统信息 - 支持大小写并转为中文
    const ua = userAgent.toLowerCase();
    const originalUA = userAgent.toUpperCase();
    
    // 统一处理系统信息，支持大小写
    if (ua.includes('android') || originalUA.includes('ANDROID')) {
        result.system = '安卓';
        result.deviceType = '手机';
    } else if (ua.includes('iphone') || originalUA.includes('IPHONE')) {
        result.system = '苹果';
        result.deviceType = '手机';
    } else if (ua.includes('ipad') || originalUA.includes('IPAD')) {
        result.system = '苹果';
        result.deviceType = '平板';
    } else if (ua.includes('windows') || originalUA.includes('WINDOWS')) {
        result.system = 'Windows';
        result.deviceType = '电脑';
    } else if (ua.includes('mac os') || ua.includes('macintosh') || 
               originalUA.includes('MAC OS') || originalUA.includes('MACINTOSH')) {
        result.system = 'macOS';
        result.deviceType = '电脑';
    } else if (ua.includes('linux') || originalUA.includes('LINUX')) {
        result.system = 'Linux';
        result.deviceType = '电脑';
    } else if (ua.includes('ios') || originalUA.includes('IOS')) {
        // iOS系统可能是iPhone或iPad
        if (ua.includes('iphone') || originalUA.includes('IPHONE')) {
            result.system = '苹果';
            result.deviceType = '手机';
        } else if (ua.includes('ipad') || originalUA.includes('IPAD')) {
            result.system = '苹果';
            result.deviceType = '平板';
        } else {
            result.system = '苹果';
            result.deviceType = '移动设备';
        }
    }

    // 解析软件信息 - 支持大小写
    if (ua.includes('micromessenger') || ua.includes('wechat') || 
        originalUA.includes('MICROMESSENGER') || originalUA.includes('WECHAT')) {
        result.software = '微信';
    } else if (ua.includes('tiktok') || ua.includes('douyin') || ua.includes('aweme') ||
               originalUA.includes('TIKTOK') || originalUA.includes('DOUYIN') || originalUA.includes('AWEME')) {
        result.software = '抖音';
    } else if (ua.includes('alipay') || originalUA.includes('ALIPAY')) {
        result.software = '支付宝';
    } else if (ua.includes('qq') || originalUA.includes('QQ')) {
        result.software = 'QQ';
    } else if (ua.includes('chrome') || originalUA.includes('CHROME')) {
        result.software = 'Chrome浏览器';
    } else if (ua.includes('safari') || originalUA.includes('SAFARI')) {
        result.software = 'Safari浏览器';
    } else if (ua.includes('firefox') || originalUA.includes('FIREFOX')) {
        result.software = 'Firefox浏览器';
    } else if (ua.includes('edge') || originalUA.includes('EDGE')) {
        result.software = 'Edge浏览器';
    }

    // 解析网络类型 - 支持大小写
    if (ua.includes('nettype/wifi') || ua.includes('wifi') || 
        originalUA.includes('NETTYPE/WIFI') || originalUA.includes('WIFI')) {
        result.networkType = 'WIFI';
    } else if (ua.includes('nettype/2g') || originalUA.includes('NETTYPE/2G')) {
        result.networkType = '2G';
    } else if (ua.includes('nettype/3g') || originalUA.includes('NETTYPE/3G')) {
        result.networkType = '3G';
    } else if (ua.includes('nettype/4g') || originalUA.includes('NETTYPE/4G')) {
        result.networkType = '4G';
    } else if (ua.includes('nettype/5g') || originalUA.includes('NETTYPE/5G')) {
        result.networkType = '5G';
    } else {
        result.networkType = '移动网络';
    }

    // 添加调试日志
    console.log('User-Agent解析结果:', {
        original: userAgent,
        parsed: result
    });
    
    return result;
}

// 生成二维码的API
app.get('/api/qrcode', async (req, res) => {
    try {
        const { communityId, jumpLinkName } = req.query;
        if (!communityId) {
            return res.status(400).json({
                success: false,
                error: '请提供地区ID'
            });
        }
        const communitiesData = readCommunities();
        const community = communitiesData.communities.find(c => c.id == communityId);
        if (!community) {
            return res.status(404).json({
                success: false,
                error: '地区不存在'
            });
        }
        // 生成跳转链接 - 包含地区信息和小程序名称
        const systemConfig = readSystemConfig();
        const baseUrl = systemConfig.baseUrl || config.baseUrl;
        let jumpUrl = `${baseUrl}/jump?communityId=${communityId}&communityName=${encodeURIComponent(community.name)}`;
        if (jumpLinkName) {
            jumpUrl += `&jumpLinkName=${encodeURIComponent(jumpLinkName)}`;
        }
        // 生成二维码 - 指向我们的跳转页面
        const qrCodeDataURL = await QRCode.toDataURL(jumpUrl, config.qrCodeConfig);
        res.json({
            success: true,
            qrCode: qrCodeDataURL,
            community: community,
            jumpUrl: jumpUrl
        });
    } catch (error) {
        console.error('生成二维码失败:', error);
        res.status(500).json({
            success: false,
            error: '生成二维码失败'
        });
    }
});

// 系统状态API
app.get('/api/status', (req, res) => {
    try {
        res.json({
            success: true,
            message: '系统运行正常',
            timestamp: new Date().toISOString(),
            targetUrl: config.targetUrl
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取系统状态失败'
        });
    }
});

// 获取外网IP的辅助函数
async function getExternalIp(req) {
    try {
        console.log('正在获取外网IP地址...');
        console.log('请求头信息:', {
            'X-Real-IP': req.get('X-Real-IP'),
            'X-Forwarded-For': req.get('X-Forwarded-For'),
            'X-Forwarded-Proto': req.get('X-Forwarded-Proto')
        });
        
        const response = await axios.get('https://api6.ipify.org/?format=json', { 
            timeout: 10000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        });
        
        console.log('API响应状态:', response.status);
        console.log('API响应数据:', response.data);
        
        if (response.data && response.data.ip) {
            console.log('✅ 成功获取外网IP:', response.data.ip);
            return response.data.ip;
        } else {
            console.log('❌ API响应格式不正确');
        }
    } catch (e) {
        console.error('❌ 获取外网IP失败:', e.message);
        if (e.code) {
            console.error('错误代码:', e.code);
        }
        if (e.response) {
            console.error('响应状态:', e.response.status);
            console.error('响应数据:', e.response.data);
        }
    }
    
    // 兜底：取本地/代理IP
    const fallbackIp = req.ip || req.connection.remoteAddress || '未知';
    console.log('使用兜底IP:', fallbackIp);
    console.log('req.ip:', req.ip);
    console.log('req.connection.remoteAddress:', req.connection.remoteAddress);
    return fallbackIp;
}

// 获取腾讯地图定位信息
async function getLocationByIp(ip, key) {
    if (!ip || !key) return null;
    try {
        const url = `https://apis.map.qq.com/ws/location/v1/ip?ip=${encodeURIComponent(ip)}&key=${encodeURIComponent(key)}`;
        const response = await axios.get(url, { timeout: 2000 });
        if (response.data && response.data.status === 0) {
            return response.data.result;
        }
    } catch (e) {
        // 忽略错误
    }
    return null;
}

// 获取百度地图逆地理编码信息
async function getBaiduLocation(lat, lng, ak) {
    if (!lat || !lng || !ak) return null;
    try {
        const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${encodeURIComponent(ak)}&extensions_poi=0&entire_poi=0&sort_strategy=distance&output=json&coordtype=wgs84ll&location=${lat},${lng}`;
        const response = await axios.get(url, { timeout: 2000 });
        if (response.data && response.data.status === 0) {
            return response.data.result;
        }
    } catch (e) {
        // 忽略错误
    }
    return null;
}

// 获取高德地图逆地理编码信息
async function getAmapLocation(lat, lng, key) {
    if (!lat || !lng || !key) return null;
    try {
        const url = `https://restapi.amap.com/v3/geocode/regeo?key=${encodeURIComponent(key)}&location=${lng},${lat}&poitype=&radius=1000&extensions=base&batch=false&roadlevel=0`;
        const response = await axios.get(url, { timeout: 2000 });
        if (response.data && response.data.status === '1') {
            return response.data.regeocode;
        }
    } catch (e) {
        // 忽略错误
    }
    return null;
}

// 记录扫码信息的API - 小程序调用
app.post('/api/record-scan', async (req, res) => {
    try {
        const { communityId, communityName, openid, unionid, jumpLinkName } = req.body;
        // 获取外网IP
        const ip = await getExternalIp(req);
        // 获取腾讯地图key、百度地图ak、高德地图key
        const systemConfig = readSystemConfig();
        const tencentMapKey = systemConfig.tencentMapKey;
        const baiduMapAk = systemConfig.baiduMapAk;
        const amapKey = systemConfig.amapKey;
        // 获取地理位置
        let location = null;
        let baiduLocation = null;
        let amapLocation = null;
        if (ip && tencentMapKey) {
            location = await getLocationByIp(ip, tencentMapKey);
            if (location && location.location) {
                if (baiduMapAk) {
                    baiduLocation = await getBaiduLocation(location.location.lat, location.location.lng, baiduMapAk);
                }
                if (amapKey) {
                    amapLocation = await getAmapLocation(location.location.lat, location.location.lng, amapKey);
                }
            }
        }
        // 记录扫码信息
        const scanRecord = {
            id: Date.now(),
            communityId: parseInt(communityId),
            communityName: communityName,
            openid: openid || null,
            unionid: unionid || null,
            jumpLinkName: jumpLinkName || null,
            scanTime: new Date().toISOString(),
            ip: ip,
            location: location,
            baiduLocation: baiduLocation,
            amapLocation: amapLocation,
            userAgent: req.get('User-Agent')
        };
        const data = readData();
        data.scanRecords.push(scanRecord);
        data.totalScans += 1;
        saveData(data);
        console.log('扫码记录:', scanRecord);
        res.json({
            success: true,
            message: '扫码记录成功',
            recordId: scanRecord.id
        });
    } catch (error) {
        console.error('记录扫码信息失败:', error);
        res.status(500).json({
            success: false,
            error: '记录扫码信息失败'
        });
    }
});

// 获取扫码统计数据的API
app.get('/api/scan-stats', (req, res) => {
    try {
        const data = readData();
        res.json({
            success: true,
            totalScans: data.totalScans,
            scanRecords: data.scanRecords.slice(-10) // 返回最近10条记录
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取统计数据失败'
        });
    }
});

// 跳转页面 - 记录扫码数据后跳转到指定链接
app.get('/jump', async (req, res) => {
    try {
        const { communityId, communityName, jumpLinkName } = req.query;
        console.log('收到扫码请求:', { communityId, communityName, jumpLinkName });
        
        // 记录扫码信息
        if (communityId && communityName) {
            const userAgent = req.get('User-Agent');
            const deviceInfo = parseUserAgent(userAgent);
            const ip = await getExternalIp(req);
            const systemConfig = readSystemConfig();
            const tencentMapKey = systemConfig.tencentMapKey;
            const baiduMapAk = systemConfig.baiduMapAk;
            const amapKey = systemConfig.amapKey;
            let location = null;
            let baiduLocation = null;
            let amapLocation = null;
            if (ip && tencentMapKey) {
                location = await getLocationByIp(ip, tencentMapKey);
                if (location && location.location) {
                    if (baiduMapAk) {
                        baiduLocation = await getBaiduLocation(location.location.lat, location.location.lng, baiduMapAk);
                    }
                    if (amapKey) {
                        amapLocation = await getAmapLocation(location.location.lat, location.location.lng, amapKey);
                    }
                }
            }
            const scanRecord = {
                id: Date.now(),
                communityId: parseInt(communityId),
                communityName: decodeURIComponent(communityName),
                jumpLinkName: jumpLinkName || null,
                scanTime: new Date().toISOString(),
                ip: ip,
                location: location,
                baiduLocation: baiduLocation,
                amapLocation: amapLocation,
                userAgent: userAgent,
                deviceInfo: deviceInfo,
                userInfo: {
                    nickname: null,
                    userId: null
                }
            };
            const data = readData();
            data.scanRecords.push(scanRecord);
            data.totalScans += 1;
            saveData(data);
            console.log('扫码记录已保存:', scanRecord);
        }
        
        // 优先使用 jumpLinks[0].url 作为 targetUrl
        const systemConfig = readSystemConfig();
        let targetUrl = config.targetUrl;
        if (systemConfig.jumpLinks && Array.isArray(systemConfig.jumpLinks) && systemConfig.jumpLinks.length > 0 && systemConfig.jumpLinks[0].url) {
            targetUrl = systemConfig.jumpLinks[0].url;
        } else if (systemConfig.targetUrl) {
            targetUrl = systemConfig.targetUrl;
        }
        
        // 直接重定向到目标链接
        return res.redirect(targetUrl);
    } catch (error) {
        console.error('跳转页面错误:', error);
        res.status(500).send('跳转失败');
    }
});

// 获取地区列表
app.get('/api/communities', (req, res) => {
    try {
        const data = readCommunities();
        res.json({
            success: true,
            communities: data.communities
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取地区列表失败'
        });
    }
});

// 添加地区
app.post('/api/communities', (req, res) => {
    try {
        const { name } = req.body;
        
        if (!name) {
            return res.status(400).json({
                success: false,
                error: '地区名称不能为空'
            });
        }
        
        const data = readCommunities();
        const newId = Math.max(...data.communities.map(c => c.id), 0) + 1;
        
        const newCommunity = {
            id: newId,
            name: name,
            active: true
        };
        
        data.communities.push(newCommunity);
        saveCommunities(data);
        
        res.json({
            success: true,
            community: newCommunity
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '添加地区失败'
        });
    }
});

// 更新地区
app.put('/api/communities/:id', (req, res) => {
    try {
        const { id } = req.params;
        const { name, active } = req.body;
        
        const data = readCommunities();
        const communityIndex = data.communities.findIndex(c => c.id == id);
        
        if (communityIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '地区不存在'
            });
        }
        
        if (name !== undefined) {
            data.communities[communityIndex].name = name;
        }
        if (active !== undefined) {
            data.communities[communityIndex].active = active;
        }
        
        saveCommunities(data);
        
        res.json({
            success: true,
            community: data.communities[communityIndex]
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '更新地区失败'
        });
    }
});

// 删除地区
app.delete('/api/communities/:id', (req, res) => {
    try {
        const { id } = req.params;
        
        const data = readCommunities();
        const communityIndex = data.communities.findIndex(c => c.id == id);
        
        if (communityIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '地区不存在'
            });
        }
        
        data.communities.splice(communityIndex, 1);
        saveCommunities(data);
        
        res.json({
            success: true,
            message: '地区删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '删除地区失败'
        });
    }
});

// 获取扫码统计
app.get('/api/statistics', (req, res) => {
    try {
        const { 
            communityId, 
            startDate, 
            endDate, 
            startTime, 
            endTime, 
            jumpLinkName, 
            year 
        } = req.query;
        const data = readData();
        const communitiesData = readCommunities();
        
        let filteredRecords = data.scanRecords;
        
        // 按小区筛选
        if (communityId) {
            filteredRecords = filteredRecords.filter(record => record.communityId == communityId);
        }
        
        // 按小程序名称筛选
        if (jumpLinkName && jumpLinkName !== '') {
            filteredRecords = filteredRecords.filter(record => record.jumpLinkName === jumpLinkName);
        }
        
        // 按年份筛选
        if (year && year !== '') {
            filteredRecords = filteredRecords.filter(record => {
                const recordYear = new Date(record.scanTime).getFullYear().toString();
                return recordYear === year;
            });
        }
        
        // 按日期筛选
        if (startDate || endDate) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordDateStr = recordDate.toISOString().split('T')[0];
                
                if (startDate && recordDateStr < startDate) return false;
                if (endDate && recordDateStr > endDate) return false;
                return true;
            });
        }
        
        // 按时间筛选
        if (startTime || endTime) {
            filteredRecords = filteredRecords.filter(record => {
                const recordTime = new Date(record.scanTime);
                const recordTimeStr = recordTime.toTimeString().split(' ')[0];
                
                if (startTime && recordTimeStr < startTime) return false;
                if (endTime && recordTimeStr > endTime) return false;
                return true;
            });
        }
        
        // 按地区统计（基于筛选后的数据）
        const communityStats = communitiesData.communities.map(community => {
            const scans = filteredRecords.filter(record => record.communityId === community.id);
            return {
                id: community.id,
                name: community.name,
                scanCount: scans.length,
                lastScan: scans.length > 0 ? scans[scans.length - 1].scanTime : null
            };
        }).sort((a, b) => b.scanCount - a.scanCount); // 按扫码次数降序排序
        
        // 今日统计
        const today = new Date().toDateString();
        const todayScans = filteredRecords.filter(record => 
            new Date(record.scanTime).toDateString() === today
        );
        
        res.json({
            success: true,
            statistics: {
                totalScans: filteredRecords.length,
                todayScans: todayScans.length,
                communityStats: communityStats,
                recentScans: filteredRecords.slice(-10).reverse() // 最近10条记录
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取统计信息失败'
        });
    }
});

// 获取扫码记录
app.get('/api/records', (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 20, 
            communityId, 
            date, 
            jumpLinkName, 
            year 
        } = req.query;
        const data = readData();
        let records = data.scanRecords;
        
        // 按小区筛选
        if (communityId) {
            records = records.filter(record => record.communityId == parseInt(communityId));
        }
        
        // 按小程序名称筛选
        if (jumpLinkName && jumpLinkName !== '') {
            records = records.filter(record => record.jumpLinkName === jumpLinkName);
        }
        
        // 按年份筛选
        if (year && year !== '') {
            records = records.filter(record => {
                const recordYear = new Date(record.scanTime).getFullYear().toString();
                return recordYear === year;
            });
        }
        
        // 按日期筛选
        if (date && date !== '') {
            records = records.filter(record => {
                try {
                    const recordDate = new Date(record.scanTime);
                    const recordDateStr = recordDate.toISOString().split('T')[0];
                    return recordDateStr === date;
                } catch (error) {
                    console.error('日期解析错误:', error);
                    return false;
                }
            });
        }
        
        // 分页
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + parseInt(limit);
        const paginatedRecords = records.slice(startIndex, endIndex);
        
        res.json({
            success: true,
            records: paginatedRecords,
            pagination: {
                page: parseInt(page),
                limit: parseInt(limit),
                total: records.length,
                totalPages: Math.ceil(records.length / limit)
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取记录失败'
        });
    }
});

// 批量删除记录 - 必须在 /api/records/:id 之前
app.delete('/api/records/batch', (req, res) => {
    try {
        console.log('=== 批量删除请求开始 ===');
        console.log('请求方法:', req.method);
        console.log('请求URL:', req.url);
        console.log('请求头:', req.headers);
        console.log('请求体:', req.body);
        console.log('请求体类型:', typeof req.body);
        
        const { recordIds } = req.body;
        
        console.log('解析的recordIds:', recordIds);
        console.log('recordIds类型:', typeof recordIds);
        console.log('recordIds是否为数组:', Array.isArray(recordIds));
        
        if (!recordIds || !Array.isArray(recordIds) || recordIds.length === 0) {
            console.log('删除参数无效:', recordIds);
            return res.status(400).json({
                success: false,
                error: '请选择要删除的记录'
            });
        }
        
        console.log('要删除的记录ID:', recordIds);
        
        const data = readData();
        console.log('当前记录总数:', data.scanRecords ? data.scanRecords.length : 0);
        
        const originalCount = data.scanRecords ? data.scanRecords.length : 0;
        
        // 删除选中的记录
        if (data.scanRecords) {
            const beforeDelete = data.scanRecords.length;
            data.scanRecords = data.scanRecords.filter(record => !recordIds.includes(record.id));
            const afterDelete = data.scanRecords.length;
            console.log(`删除前: ${beforeDelete} 条记录，删除后: ${afterDelete} 条记录`);
        } else {
            data.scanRecords = [];
        }
        
        data.totalScans = data.scanRecords.length;
        saveData(data);
        
        const deletedCount = originalCount - data.scanRecords.length;
        console.log('删除成功，删除了', deletedCount, '条记录');
        
        res.json({
            success: true,
            message: '批量删除成功',
            deletedCount: deletedCount
        });
        
        console.log('=== 批量删除请求完成 ===');
    } catch (error) {
        console.error('=== 批量删除失败 ===');
        console.error('错误信息:', error.message);
        console.error('错误堆栈:', error.stack);
        res.status(500).json({
            success: false,
            error: '批量删除失败: ' + error.message
        });
    }
});

// 删除筛选的记录
app.delete('/api/records/filtered', (req, res) => {
    try {
        const { 
            communityId, 
            startDate, 
            endDate, 
            startTime, 
            endTime 
        } = req.query;
        const data = readData();
        
        let recordsToDelete = data.scanRecords;
        
        // 按地区筛选
        if (communityId) {
            recordsToDelete = recordsToDelete.filter(record => record.communityId == communityId);
        }
        
        // 按日期筛选
        if (startDate || endDate) {
            recordsToDelete = recordsToDelete.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordDateStr = recordDate.toISOString().split('T')[0];
                
                if (startDate && recordDateStr < startDate) return false;
                if (endDate && recordDateStr > endDate) return false;
                return true;
            });
        }
        
        // 按时间筛选
        if (startTime || endTime) {
            recordsToDelete = recordsToDelete.filter(record => {
                const recordTime = new Date(record.scanTime);
                const recordTimeStr = recordTime.toTimeString().split(' ')[0];
                
                if (startTime && recordTimeStr < startTime) return false;
                if (endTime && recordTimeStr > endTime) return false;
                return true;
            });
        }
        
        // 删除筛选的记录
        const deletedIds = recordsToDelete.map(record => record.id);
        data.scanRecords = data.scanRecords.filter(record => !deletedIds.includes(record.id));
        data.totalScans = data.scanRecords.length;
        saveData(data);
        
        res.json({
            success: true,
            message: '筛选记录删除成功',
            deletedCount: deletedIds.length
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '删除筛选记录失败'
        });
    }
});

// 删除全部记录
app.delete('/api/records/all', (req, res) => {
    try {
        const data = readData();
        const deletedCount = data.scanRecords.length;
        
        data.scanRecords = [];
        data.totalScans = 0;
        saveData(data);
        
        res.json({
            success: true,
            message: '全部记录删除成功',
            deletedCount: deletedCount
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '删除全部记录失败'
        });
    }
});

// 获取扫码记录日期列表
app.get('/api/records/dates', (req, res) => {
    try {
        const { communityId } = req.query;
        const data = readData();
        
        let records = data.scanRecords;
        
        // 按地区筛选
        if (communityId) {
            records = records.filter(record => record.communityId == communityId);
        }
        
        // 提取所有日期并去重
        const dates = [...new Set(records.map(record => {
            const recordDate = new Date(record.scanTime);
            return recordDate.toISOString().split('T')[0];
        }))].sort();
        
        res.json({
            success: true,
            dates: dates
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取日期列表失败'
        });
    }
});

// 获取扫码记录可用年份和日期
app.get('/api/records/years-dates', (req, res) => {
    try {
        const { communityId, jumpLinkName, year, month } = req.query;
        const data = readData();
        let records = data.scanRecords;
        if (communityId) {
            records = records.filter(record => record.communityId == communityId);
        }
        if (jumpLinkName && jumpLinkName !== '') {
            records = records.filter(record => record.jumpLinkName === jumpLinkName);
        }
        if (year && year !== '') {
            records = records.filter(record => {
                const recordYear = new Date(record.scanTime).getFullYear().toString();
                return recordYear === year;
            });
        }
        if (month && month !== '') {
            records = records.filter(record => {
                const recordMonth = new Date(record.scanTime).toISOString().substring(0, 7);
                return recordMonth === month;
            });
        }
        // 年份
        const years = [...new Set(records.map(record => {
            return new Date(record.scanTime).getFullYear().toString();
        }))].sort();
        // 月份
        const months = [...new Set(records.map(record => {
            return new Date(record.scanTime).toISOString().substring(0, 7);
        }))].sort();
        // 日期
        const dates = [...new Set(records.map(record => {
            return new Date(record.scanTime).toISOString().split('T')[0];
        }))].sort();
        res.json({
            success: true,
            years,
            months,
            dates
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取年份和日期失败'
        });
    }
});

// 删除单条记录 - 必须在具体路由之后
app.delete('/api/records/:id', (req, res) => {
    try {
        const { id } = req.params;
        const data = readData();
        
        const recordIndex = data.scanRecords.findIndex(record => record.id == id);
        
        if (recordIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '记录不存在'
            });
        }
        
        data.scanRecords.splice(recordIndex, 1);
        data.totalScans = data.scanRecords.length;
        saveData(data);
        
        res.json({
            success: true,
            message: '记录删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '删除记录失败'
        });
    }
});

// 导出地区统计
app.get('/api/community-stats/export', (req, res) => {
    try {
        const { sortBy = 'total', order = 'desc', year, month, date, jumpLinkName } = req.query;
        const data = readData();
        const communitiesData = readCommunities();
        let filteredRecords = data.scanRecords;
        // 按年份筛选
        if (year) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordYear = recordDate.getFullYear().toString();
                return recordYear === year;
            });
        }
        // 按月份筛选
        if (month) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordMonth = recordDate.toISOString().substring(0, 7);
                return recordMonth === month;
            });
        }
        // 按日期筛选
        if (date) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordDateStr = recordDate.toISOString().split('T')[0];
                return recordDateStr === date;
            });
        }
        // 按跳转链接筛选
        if (jumpLinkName && jumpLinkName !== '') {
            filteredRecords = filteredRecords.filter(record => record.jumpLinkName === jumpLinkName);
        }
        // 地区统计
        let communityStats = communitiesData.communities.map(community => {
            const filteredScans = filteredRecords.filter(record => record.communityId === community.id);
            // 今日扫码次数
            const todayStr = new Date().toISOString().split('T')[0];
            const todayScans = filteredScans.filter(record => {
                const recordDateStr = new Date(record.scanTime).toISOString().split('T')[0];
                return recordDateStr === todayStr;
            }).length;
            // 统计最多的跳转链接
            let jumpName = '';
            if (filteredScans.length > 0) {
                const nameCount = {};
                filteredScans.forEach(r => {
                    if (r.jumpLinkName) {
                        nameCount[r.jumpLinkName] = (nameCount[r.jumpLinkName] || 0) + 1;
                    }
                });
                let max = 0;
                for (const n in nameCount) {
                    if (nameCount[n] > max) {
                        max = nameCount[n];
                        jumpName = n;
                    }
                }
            }
            return {
                name: community.name,
                totalScans: filteredScans.length,
                todayScans: todayScans,
                jumpLinkName: jumpName
            };
        }).filter(stat => stat.totalScans > 0);
        // 排序
        if (sortBy === 'today') {
            communityStats.sort((a, b) => order === 'desc' ? b.todayScans - a.todayScans : a.todayScans - b.todayScans);
        } else {
            communityStats.sort((a, b) => order === 'desc' ? b.totalScans - a.totalScans : a.totalScans - b.totalScans);
        }
        // 导出表头与前端一致
        const csvHeader = '地区名称,总扫码次数,今日扫码次数,跳转链接\n';
        const csvContent = communityStats.map(stat => {
            return `"${stat.name}","${stat.totalScans}","${stat.todayScans}","${stat.jumpLinkName}"`;
        }).join('\n');
        const csvData = csvHeader + csvContent;
        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename="community_stats_${new Date().toISOString().split('T')[0]}.csv"`);
        res.send(csvData);
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '导出地区统计失败: ' + error.message
        });
    }
});

// 修复 /api/records/export，支持 jumpLinkName 和 year 筛选
app.get('/api/records/export', (req, res) => {
    try {
        console.log('=== 开始导出记录 ===');
        console.log('请求参数:', req.query);
        const { communityId, date, jumpLinkName, year } = req.query;
        // 读取数据
        console.log('正在读取数据文件...');
        const data = readData();
        console.log('数据读取成功，记录数:', data.scanRecords ? data.scanRecords.length : 0);
        let records = data.scanRecords || [];
        // 按条件筛选
        if (communityId) {
            records = records.filter(record => record.communityId == communityId);
        }
        if (date) {
            records = records.filter(record => (record.scanTime || '').startsWith(date));
        }
        if (jumpLinkName && jumpLinkName !== '') {
            records = records.filter(record => record.jumpLinkName === jumpLinkName);
        }
        if (year && year !== '') {
            records = records.filter(record => {
                const recordYear = new Date(record.scanTime).getFullYear().toString();
                return recordYear === year;
            });
        }
        // 导出内容：时间、地区、地址信息、设备信息、小程序名称
        const csvHeader = '时间,地区,地址信息,设备系统,设备软件,网络类型,设备类型,跳转链接\n';
        let csvContent = '';
        records.forEach(record => {
            try {
                const time = new Date(record.scanTime).toLocaleString('zh-CN');
                const communityName = record.communityName || '未知';
                // 地址信息与前端一致
                let addrInfo = record.ip || '';
                let coordStr = '';
                if (record.location && record.location.location) {
                    const loc = record.location.location;
                    coordStr = ` 坐标:(${loc.lat},${loc.lng})`;
                }
                if (record.baiduLocation && (record.baiduLocation.formatted_address || record.baiduLocation.business)) {
                    let addr = record.baiduLocation.formatted_address || '';
                    let business = record.baiduLocation.business || '';
                    let district = '';
                    if (addr) {
                        const match = addr.match(/^(.*?市.*?区)/);
                        if (match) {
                            district = match[1];
                        } else {
                            const match2 = addr.match(/^(.*?市.*?县)/);
                            if (match2) district = match2[1];
                        }
                    }
                    let businessName = business.split(',')[0] || '';
                    addrInfo = `${district}${businessName ? businessName : ''}${coordStr}`;
                } else if (record.amapLocation && (record.amapLocation.addressComponent || record.amapLocation.formatted_address)) {
                    let ac = record.amapLocation.addressComponent || {};
                    let province = ac.province || '';
                    let city = ac.city || '';
                    let district = ac.district || '';
                    let street = ac.township || ac.street || '';
                    let poi = '';
                    if (record.amapLocation.pois && record.amapLocation.pois.length > 0) {
                        poi = record.amapLocation.pois[0].name;
                    }
                    let addr = `${province}${city}${district}${street}${poi}`;
                    if (!addr) addr = record.amapLocation.formatted_address || '';
                    addrInfo = `${addr}${coordStr}`;
                } else if (coordStr) {
                    addrInfo += coordStr;
                }
                const deviceInfo = record.deviceInfo || {};
                const row = `"${time}","${communityName}","${addrInfo}","${deviceInfo.system || '未知'}","${deviceInfo.software || '未知'}","${deviceInfo.networkType || '未知'}","${deviceInfo.deviceType || '未知'}","${record.jumpLinkName || ''}"`;
                csvContent += row + '\n';
            } catch (error) {
                const fallbackRow = `"${new Date().toLocaleString('zh-CN')}","未知","未知","未知","未知","未知","未知",""`;
                csvContent += fallbackRow + '\n';
            }
        });
        const csvData = csvHeader + csvContent;
        res.setHeader('Content-Type', 'text/csv; charset=utf-8');
        res.setHeader('Content-Disposition', `attachment; filename="scan_records_${new Date().toISOString().split('T')[0]}.csv"`);
        res.send(csvData);
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '导出记录失败: ' + error.message
        });
    }
});

// 测试路由
app.get('/test', (req, res) => {
    res.send('测试路由正常 - 服务器运行正常');
});

// 获取系统配置
app.get('/api/system-config', (req, res) => {
    try {
        const systemConfig = readSystemConfig();
        res.json({
            success: true,
            config: systemConfig
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取系统配置失败'
        });
    }
});

// 更新系统配置
app.put('/api/system-config', (req, res) => {
    try {
        const { jumpLinks, baseUrl, tencentMapKey, baiduMapAk, amapKey } = req.body;
        if (!jumpLinks || !Array.isArray(jumpLinks) || jumpLinks.length === 0 || jumpLinks.some(j => !j.name || !j.url)) {
            return res.status(400).json({
                success: false,
                error: '跳转链接配置不能为空'
            });
        }
        if (!baseUrl) {
            return res.status(400).json({
                success: false,
                error: '基础URL不能为空'
            });
        }
        const currentConfig = readSystemConfig();
        const updatedConfig = {
            ...currentConfig,
            jumpLinks,
            baseUrl,
            tencentMapKey,
            baiduMapAk,
            amapKey,
            lastUpdated: new Date().toISOString()
        };
        saveSystemConfig(updatedConfig);
        config.baseUrl = baseUrl;
        console.log('系统配置已更新:', updatedConfig);
        res.json({
            success: true,
            message: '系统配置更新成功',
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '系统配置更新失败: ' + error.message
        });
    }
});

// 测试axios是否正常工作
app.get('/test-axios', async (req, res) => {
    try {
        console.log('测试axios...');
        const resp = await axios.get('https://httpbin.org/get', {
            timeout: 5000
        });
        console.log('axios测试成功:', resp.status);
        res.json({
            success: true,
            message: 'axios工作正常',
            status: resp.status
        });
    } catch (error) {
        console.error('axios测试失败:', error.message);
        res.json({
            success: false,
            error: 'axios测试失败: ' + error.message
        });
    }
});

// 简单测试页面
app.get('/simple-test', (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>简单测试</title>
        </head>
        <body>
            <h1>服务器运行正常！</h1>
            <p>如果您能看到这个页面，说明服务器工作正常。</p>
            <a href="/api/test-urllink">测试URL Link生成</a>
        </body>
        </html>
    `);
});

// 简化版跳转页面测试
app.get('/jump-test', async (req, res) => {
    try {
        const { communityId, communityName } = req.query;
        
        console.log('测试跳转页面 - 收到请求:', { communityId, communityName });
        
        // 记录扫码信息
        if (communityId && communityName) {
            const userAgent = req.get('User-Agent');
            const deviceInfo = parseUserAgent(userAgent);
            const ip = await getExternalIp(req);
            const systemConfig = readSystemConfig();
            const tencentMapKey = systemConfig.tencentMapKey;
            const baiduMapAk = systemConfig.baiduMapAk;
            const amapKey = systemConfig.amapKey;
            let location = null;
            let baiduLocation = null;
            let amapLocation = null;
            if (ip && tencentMapKey) {
                location = await getLocationByIp(ip, tencentMapKey);
                if (location && location.location) {
                    if (baiduMapAk) {
                        baiduLocation = await getBaiduLocation(location.location.lat, location.location.lng, baiduMapAk);
                    }
                    if (amapKey) {
                        amapLocation = await getAmapLocation(location.location.lat, location.location.lng, amapKey);
                    }
                }
            }
            const scanRecord = {
                id: Date.now(),
                communityId: parseInt(communityId),
                communityName: decodeURIComponent(communityName),
                scanTime: new Date().toISOString(),
                ip: ip,
                location: location,
                baiduLocation: baiduLocation,
                amapLocation: amapLocation,
                userAgent: userAgent,
                deviceInfo: deviceInfo,
                userInfo: {
                    nickname: null,
                    userId: null
                }
            };
            
            const data = readData();
            data.scanRecords.push(scanRecord);
            data.totalScans += 1;
            saveData(data);
            
            console.log('扫码记录已保存:', scanRecord);
        }
        
        // 优先使用 jumpLinks[0].url 作为 targetUrl
        const systemConfig = readSystemConfig();
        let targetUrl = config.targetUrl;
        if (systemConfig.jumpLinks && Array.isArray(systemConfig.jumpLinks) && systemConfig.jumpLinks.length > 0 && systemConfig.jumpLinks[0].url) {
            targetUrl = systemConfig.jumpLinks[0].url;
        } else if (systemConfig.targetUrl) {
            targetUrl = systemConfig.targetUrl;
        }
        
        // 返回简单的HTML页面
        res.send(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>跳转中...</title>
                <meta charset="UTF-8">
            </head>
            <body>
                <h1>数据已保存，正在进入...</h1>
                <p>目标链接: ${targetUrl}</p>
                <p>如果没有自动跳转，请点击下方链接</p>
                <a href="${targetUrl}" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">手动跳转</a>
                
                <div id="debug" style="margin-top: 20px; padding: 10px; background: #f0f0f0;">
                    <h3>调试信息:</h3>
                    <p>页面加载时间: <span id="loadTime"></span></p>
                    <p>跳转状态: <span id="status">准备中...</span></p>
                    <p>地区信息: ${communityName ? decodeURIComponent(communityName) : '未知'}</p>
                </div>
                
                <script>
                    document.getElementById('loadTime').textContent = new Date().toLocaleString();
                    
                    var targetUrl = '${targetUrl}';
                    console.log('准备跳转到:', targetUrl);
                    document.getElementById('status').textContent = '准备跳转...';
                    
                    setTimeout(function() {
                        console.log('开始跳转...');
                        document.getElementById('status').textContent = '正在跳转...';
                        window.location.href = targetUrl;
                    }, 1000);
                    
                    // 如果5秒后还在当前页面，显示提示
                    setTimeout(function() {
                        if (document.visibilityState !== 'hidden') {
                            document.getElementById('status').textContent = '跳转可能失败，请手动点击链接';
                            console.log('跳转可能失败，请手动点击');
                        }
                    }, 5000);
                </script>
            </body>
            </html>
        `);
    } catch (error) {
        console.error('跳转页面错误:', error);
        res.status(500).send('跳转失败: ' + error.message);
    }
});

// 主页
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 登录页面路由
app.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'login.html'));
});

// 登录API
app.post('/api/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        if (!username || !password) {
            return res.status(400).json({ success: false, error: '用户名或密码不能为空' });
        }
        const usersData = JSON.parse(fs.readFileSync('users.json', 'utf8'));
        const user = usersData.users.find(u => u.username === username);
        if (!user) {
            return res.status(404).json({ success: false, error: '用户不存在' });
        }
        const match = await bcrypt.compare(password, user.password);
        if (!match) {
            return res.status(400).json({ success: false, error: '密码错误' });
        }
        res.json({ success: true, message: '登录成功' });
    } catch (error) {
        res.status(500).json({ success: false, error: '登录失败: ' + error.message });
    }
});

// 恢复 /api/community-statistics 接口
app.get('/api/community-statistics', (req, res) => {
    try {
        const { sortBy = 'total', year, month, date, jumpLinkName, order = 'desc' } = req.query;
        const data = readData();
        const communitiesData = readCommunities();
        let filteredRecords = data.scanRecords;
        if (year) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordYear = recordDate.getFullYear().toString();
                return recordYear === year;
            });
        }
        if (month) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordMonth = recordDate.toISOString().substring(0, 7);
                return recordMonth === month;
            });
        }
        if (date) {
            filteredRecords = filteredRecords.filter(record => {
                const recordDate = new Date(record.scanTime);
                const recordDateStr = recordDate.toISOString().split('T')[0];
                return recordDateStr === date;
            });
        }
        if (jumpLinkName && jumpLinkName !== '') {
            filteredRecords = filteredRecords.filter(record => record.jumpLinkName === jumpLinkName);
        }
        const todayStr = new Date().toISOString().split('T')[0];
        let communityStats = communitiesData.communities.map(community => {
            const filteredScans = filteredRecords.filter(record => record.communityId === community.id);
            // 今日扫码次数
            const todayScans = filteredScans.filter(record => {
                const recordDateStr = new Date(record.scanTime).toISOString().split('T')[0];
                return recordDateStr === todayStr;
            }).length;
            // 统计最多的小程序名称
            let jumpName = '';
            let phoneNumber = '';
            if (filteredScans.length > 0) {
                const nameCount = {};
                const phoneCount = {};
                filteredScans.forEach(r => {
                    if (r.jumpLinkName) {
                        nameCount[r.jumpLinkName] = (nameCount[r.jumpLinkName] || 0) + 1;
                    }
                    if (r.phoneNumber) {
                        phoneCount[r.phoneNumber] = (phoneCount[r.phoneNumber] || 0) + 1;
                    }
                });
                let max = 0;
                for (const n in nameCount) {
                    if (nameCount[n] > max) {
                        max = nameCount[n];
                        jumpName = n;
                    }
                }
                // 取出现次数最多的手机号
                max = 0;
                for (const p in phoneCount) {
                    if (phoneCount[p] > max) {
                        max = phoneCount[p];
                        phoneNumber = p;
                    }
                }
            }
            return {
                id: community.id,
                name: community.name,
                totalScans: filteredScans.length,
                todayScans: todayScans,
                jumpLinkName: jumpName,
                phoneNumber: phoneNumber
            };
        }).filter(stat => stat.totalScans > 0);
        if (sortBy === 'today') {
            communityStats.sort((a, b) => order === 'desc' ? b.todayScans - a.todayScans : a.todayScans - b.todayScans);
        } else {
            communityStats.sort((a, b) => order === 'desc' ? b.totalScans - a.totalScans : a.totalScans - b.totalScans);
        }
        // 计算时间段统计（始终用filteredRecords，确保小程序筛选生效）
        function calculateTimeSlotStats(records) {
            const timeSlots = {};
            const communitiesData = readCommunities();
            // 初始化24个时间段（每2小时一个）
            for (let i = 0; i < 24; i += 2) {
                const startHour = i.toString().padStart(2, '0');
                const endHour = (i + 2).toString().padStart(2, '0');
                const timeSlot = `${startHour}:00-${endHour}:00`;
                timeSlots[timeSlot] = 0;
            }
            // 统计每个时间段的扫码次数
            records.forEach(record => {
                const recordTime = new Date(record.scanTime);
                const hour = recordTime.getHours();
                const slotIndex = Math.floor(hour / 2) * 2;
                const startHour = slotIndex.toString().padStart(2, '0');
                const endHour = (slotIndex + 2).toString().padStart(2, '0');
                const timeSlot = `${startHour}:00-${endHour}:00`;
                timeSlots[timeSlot]++;
            });
            // 转换为数组并排序
            const timeSlotArray = Object.entries(timeSlots).map(([timeSlot, count]) => ({
                timeSlot,
                count
            })).sort((a, b) => b.count - a.count);
            // 找出最高和最低的时间段
            const maxSlot = timeSlotArray[0];
            const minSlot = timeSlotArray[timeSlotArray.length - 1];
            // 计算各地区扫码次数
            const communityStats = communitiesData.communities.map(community => {
                const communityRecords = records.filter(record => record.communityId === community.id);
                return {
                    id: community.id,
                    name: community.name,
                    scanCount: communityRecords.length
                };
            }).sort((a, b) => b.scanCount - a.scanCount);
            // 找出最高和最低扫码地区
            const maxCommunity = communityStats[0];
            const minCommunity = communityStats[communityStats.length - 1];
            return {
                timeSlots: timeSlotArray,
                maxTimeSlot: maxSlot,
                minTimeSlot: minSlot,
                maxCommunity: maxCommunity,
                minCommunity: minCommunity,
                totalScans: records.length
            };
        }
        let timeSlotStats = calculateTimeSlotStats(filteredRecords);
        res.json({
            success: true,
            communityStats: communityStats,
            timeSlotStats: timeSlotStats,
            filterInfo: {
                year: year,
                month: month,
                date: date,
                jumpLinkName: jumpLinkName,
                sortBy: sortBy,
                order: order
            }
        });
    } catch (error) {
        res.status(500).json({ success: false, error: '获取地区统计失败' });
    }
});

// 地区统计可用日期接口
app.get('/api/available-dates', (req, res) => {
    try {
        const { year, month } = req.query;
        const data = readData();
        let records = data.scanRecords;
        // 按年筛选
        if (year) {
            records = records.filter(record => {
                const recordYear = new Date(record.scanTime).getFullYear().toString();
                return recordYear === year;
            });
        }
        // 按月筛选
        if (month) {
            records = records.filter(record => {
                const recordMonth = new Date(record.scanTime).toISOString().substring(0, 7);
                return recordMonth === month;
            });
        }
        // 提取所有年、月、日
        const years = [...new Set(records.map(r => new Date(r.scanTime).getFullYear().toString()))].sort();
        const months = [...new Set(records.map(r => new Date(r.scanTime).toISOString().substring(0, 7)))].sort();
        const dates = [...new Set(records.map(r => new Date(r.scanTime).toISOString().split('T')[0]))].sort();
        res.json({
            success: true,
            years,
            months,
            dates
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: '获取可用日期失败'
        });
    }
});

// 修改密码API
app.post('/api/change-password', async (req, res) => {
    try {
        const { username, currentPassword, newPassword } = req.body;
        if (!username || !currentPassword || !newPassword) {
            return res.status(400).json({ success: false, error: '参数不完整' });
        }
        const usersData = JSON.parse(fs.readFileSync('users.json', 'utf8'));
        const user = usersData.users.find(u => u.username === username);
        if (!user) {
            return res.status(404).json({ success: false, error: '用户不存在' });
        }
        const match = await bcrypt.compare(currentPassword, user.password);
        if (!match) {
            return res.status(400).json({ success: false, error: '当前密码错误' });
        }
        if (currentPassword === newPassword) {
            return res.status(400).json({ success: false, error: '新密码不能与原密码相同' });
        }
        const hash = await bcrypt.hash(newPassword, 10);
        user.password = hash;
        fs.writeFileSync('users.json', JSON.stringify(usersData, null, 2));
        res.json({ success: true, message: '密码修改成功' });
    } catch (error) {
        res.status(500).json({ success: false, error: '密码修改失败: ' + error.message });
    }
});

function getDomainFromConfig() {
    // 优先用 config.productionDomain
    if (config.productionDomain && typeof config.productionDomain === 'string' && config.productionDomain.trim()) {
        return config.productionDomain.trim();
    }
    // fallback 到 system-config.json 的 baseUrl
    try {
        const sysConfigPath = config.configFile || 'system-config.json';
        if (fs.existsSync(sysConfigPath)) {
            const sysConfig = JSON.parse(fs.readFileSync(sysConfigPath, 'utf8'));
            if (sysConfig.baseUrl && typeof sysConfig.baseUrl === 'string') {
                // 提取主机名
                const match = sysConfig.baseUrl.match(/^https?:\/\/([^/:]+)/);
                if (match && match[1]) return match[1];
            }
        }
    } catch (e) {}
    return null;
}

function startServer() {
    const HTTPS_PORT = process.env.HTTPS_PORT || 10443;
    const domain = getDomainFromConfig();
    let sslKeyPath = null;
    let sslCertPath = null;
    if (domain) {
        sslKeyPath = `/app/ssl/${domain}.key`;
        sslCertPath = `/app/ssl/${domain}.crt`;
    }
    // 检查SSL证书文件
    if (sslKeyPath && sslCertPath && fs.existsSync(sslKeyPath) && fs.existsSync(sslCertPath)) {
        // 启动HTTPS服务器
        const httpsOptions = {
            key: fs.readFileSync(sslKeyPath),
            cert: fs.readFileSync(sslCertPath)
        };
        const httpsServer = https.createServer(httpsOptions, app);
        httpsServer.listen(HTTPS_PORT, '0.0.0.0', () => {
            console.log(`🚀 HTTPS服务器启动成功！`);
            console.log(`🔒 HTTPS访问: https://localhost:${HTTPS_PORT}`);
            console.log(`🎯 跳转链接: ${config.targetUrl}`);
            console.log(`📊 管理界面: https://localhost:${HTTPS_PORT}`);
            console.log(`🔧 系统状态: https://localhost:${HTTPS_PORT}/api/status`);
        });
        // 同时启动HTTP服务器（重定向到HTTPS）
        app.listen(PORT, '0.0.0.0', () => {
            console.log(`🌐 HTTP服务器启动成功！`);
            console.log(`📱 HTTP访问: http://localhost:${PORT}`);
            console.log(`🔄 HTTP将重定向到HTTPS`);
        });
    } else {
        // 只启动HTTP服务器
        app.listen(PORT, '0.0.0.0', () => {
            console.log(`🚀 HTTP服务器启动成功！`);
            console.log(`📱 本地访问: http://localhost:${PORT}`);
            console.log(`🎯 跳转链接: ${config.targetUrl}`);
            console.log(`📊 管理界面: http://localhost:${PORT}`);
            console.log(`🔧 系统状态: http://localhost:${PORT}/api/status`);
            if (!domain) {
                console.log(`⚠️  未检测到域名配置（config.js的productionDomain或system-config.json的baseUrl），仅提供HTTP服务`);
            } else {
                console.log(`⚠️  未找到SSL证书，仅提供HTTP服务`);
            }
        });
    }
}

startServer(); 